<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>H2 Database Select 语句执行流程 | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="H2 Database Select 语句执行流程使用1234&#x2F;&#x2F; CREATE TABLE IF NOT EXISTS test(id INT primary key, name VARCHAR(255))&#x2F;&#x2F; insert into test(id, name) values(1, &#x27;name1&#x27;), (2, &#x27;name2&#x27;), (3, &#x27;na">
<meta property="og:type" content="article">
<meta property="og:title" content="H2 Database Select 语句执行流程">
<meta property="og:url" content="https://flyingzc.github.io/articles/h2/h2database12-select.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="H2 Database Select 语句执行流程使用1234&#x2F;&#x2F; CREATE TABLE IF NOT EXISTS test(id INT primary key, name VARCHAR(255))&#x2F;&#x2F; insert into test(id, name) values(1, &#x27;name1&#x27;), (2, &#x27;name2&#x27;), (3, &#x27;na">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2024-10-23T16:00:00.000Z">
<meta property="article:modified_time" content="2025-05-09T00:21:00.357Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="H2">
<meta property="article:tag" content="Database">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "H2 Database Select 语句执行流程",
  "url": "https://flyingzc.github.io/articles/h2/h2database12-select.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2024-10-23T16:00:00.000Z",
  "dateModified": "2025-05-09T00:21:00.357Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/h2/h2database12-select.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'H2 Database Select 语句执行流程',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">H2 Database Select 语句执行流程</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">H2 Database Select 语句执行流程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-10-23T16:00:00.000Z" title="发表于 2024-10-24 00:00:00">2024-10-24</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-05-09T00:21:00.357Z" title="更新于 2025-05-09 08:21:00">2025-05-09</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/H2/">H2</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="H2-Database-Select-语句执行流程"><a href="#H2-Database-Select-语句执行流程" class="headerlink" title="H2 Database Select 语句执行流程"></a>H2 Database Select 语句执行流程</h1><h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// CREATE TABLE IF NOT EXISTS test(id INT primary key, name VARCHAR(255))</span><br><span class="hljs-comment">// insert into test(id, name) values(1, &#x27;name1&#x27;), (2, &#x27;name2&#x27;), (3, &#x27;name3&#x27;), (4, &#x27;name4&#x27;);</span><br><span class="hljs-type">String</span> <span class="hljs-variable">sql</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;SELECT * FROM test where id &gt; 1 and name=&#x27;name3&#x27;&quot;</span>;<br><span class="hljs-type">ResultSet</span> <span class="hljs-variable">rs</span> <span class="hljs-operator">=</span> stmt.executeQuery(sql);<br></code></pre></td></tr></table></figure>

<p>查询 case:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs km">主键查询<br>覆盖索引查询<br>索引查询+回表<br>多表关联查询<br></code></pre></td></tr></table></figure>

<h2 id="功能"><a href="#功能" class="headerlink" title="功能"></a>功能</h2><h2 id="模块"><a href="#模块" class="headerlink" title="模块"></a>模块</h2><h2 id="类"><a href="#类" class="headerlink" title="类"></a>类</h2><h2 id="总体流程"><a href="#总体流程" class="headerlink" title="总体流程"></a>总体流程</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs km">Select 语句 SQL 解析<br>Select 语句 SQL 查询优化<br>  计算执行计划的成本<br>    创建查询优化器<br>    优化查询计划<br>      计算最佳查询计划<br>        测试并更新最优查询计划<br>          创建计划<br>          计算计划成本<br>            先计算 MVPrimaryIndex 查询计划的成本<br>            再获取所有候选的索引计算对应的查询计划<br>            更新成本最低的查询计划并返回<br>Select 语句执行<br></code></pre></td></tr></table></figure>

<h3 id="解析-优化"><a href="#解析-优化" class="headerlink" title="解析&amp;优化"></a>解析&amp;优化</h3><p>H2 在执行查询操作之前，会根据不同索引计算对应的成本，然后选择成本最小的索引进行后续查询操作。<br>单表查询时，会获取表的所有索引。按照主键索引、二级索引的顺序依次计算对应的成本。<br>然后选择成本最小的索引作为查询计划。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><code class="hljs km">org.h2.command.Parser#parse <br>解析sql<br>org.h2.command.query.Query#prepare <br>优化sql<br>    org.h2.command.query.Select#preparePlan <br>    计算执行计划的成本<br>          org.h2.command.query.Optimizer#&lt;init&gt; <br>          创建查询优化器<br>          org.h2.command.query.Optimizer#optimize <br>          优化查询计划<br>              org.h2.command.query.Optimizer#calculateBestPlan <br>              计算最佳查询计划<br>                  org.h2.command.query.Optimizer#testPlan <br>                  测试并更新最优计划<br>                      org.h2.table.Plan#&lt;init&gt; <br>                      创建一个计划<br>                      org.h2.table.Plan#calculateCost <br>                      计算计划成本<br>                          初始化成本为1，作为后续成本累乘的基础值<br>                          遍历所有的表过滤器来计算总成本<br>                          org.h2.table.TableFilter#getBestPlanItem <br>                          获取最佳的计划项<br>                              org.h2.table.Table#getBestPlanItem <br>                              获取最佳的计划项<br>                                  org.h2.table.PlanItem#&lt;init&gt; <br>                                  初始化一个 PlanItem 对象来存储最佳计划<br>                                  org.h2.mvstore.db.MVPrimaryIndex#getCost <br>                                  计算初始计划项的成本(primary key)<br>                                      org.h2.index.Index#getCostRangeIndex<br>                                      具体计算成本<br>                                  org.h2.mvstore.db.MVTable#getIndexes <br>                                  获取所有候选索引<br>                                  遍历所有索引<br>                                  计算当前索引的成本(不同索引有不同索引的计算公式)<br>                                  如果当前索引的成本低于当前最佳计划项的成本，更新最佳计划项<br>                          更新总成本<br>                          返回最终计算的成本<br>                          选择最优计划<br></code></pre></td></tr></table></figure>

<h3 id="执行"><a href="#执行" class="headerlink" title="执行"></a>执行</h3><p>执行查询时，会根据上面选定的索引创建对应的迭代器，同时会根据不同的事务隔离级别选择创建不同隔离级别的迭代器（比如 CommittedIterator）。<br>然后根据索引列的条件迭代索引获取数据，获取后的数据会通过 <code>isConditionMet</code> 判断是否满足 SQL 查询条件，最终决定是否要把该行返回给客户端。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs km">org.h2.command.query.Select#queryWithoutCache<br>执行查询<br>    org.h2.table.TableFilter#lock <br>    加读锁<br>    org.h2.command.query.Select#queryFlat<br>    执行查询<br>        org.h2.result.LazyResult#init0 <br>        创建一个LazyResultQueryFlat对象<br>        org.h2.result.FetchedResult#next <br>        获取下一行<br>            org.h2.result.LazyResult#hasNext <br>            判断是否有下一条记录<br>                org.h2.command.query.Select.LazyResultQueryFlat#fetchNextRow <br>                获取下一行<br>                    org.h2.table.TableFilter#next <br>                    获取下一行数据<br>                        org.h2.index.IndexCursor#find <br>                        创建 index cursor, 用于迭代数据<br>                            org.h2.index.IndexCursor#prepare<br>                            org.h2.mvstore.db.MVPrimaryIndex#find <br>                            从 index 里获取 row, 比如 primary index<br>                                org.h2.mvstore.db.MVPrimaryIndex#getMap <br>                                获取 transaction map<br>                                org.h2.mvstore.tx.TransactionMap#entryIterator <br>                                根据不同隔离级别创建不同迭代器，比如 CommittedIterator<br>                        org.h2.index.IndexCursor#next <br>                        通过迭代器获取下一行数据<br>                            org.h2.mvstore.db.MVPrimaryIndex.MVStoreCursor#next <br>                            通过主键索引获取下一行数据<br>                                org.h2.mvstore.tx.TransactionMap.CommittedIterator#fetchNext <br>                                获取读已提交数据<br>                                    org.h2.mvstore.Cursor#hasNext <br>                                    迭代到叶子节点获取下一行数据,返回是否存在下一行数据<br>                                        org.h2.mvstore.Page.Leaf#getValue<br>                                        获取当前值<br>                                    org.h2.mvstore.Cursor#next <br>                                    获取下一行数据<br>                    org.h2.command.query.Select#isConditionMet<br>                    判断当前行是否满足查询条件<br></code></pre></td></tr></table></figure>

<h4 id="迭代索引获取数据"><a href="#迭代索引获取数据" class="headerlink" title="迭代索引获取数据"></a>迭代索引获取数据</h4><p><code>Cursor#hasNext</code> 方法主要用于判断迭代器是否还有下一个元素。<br>如果有下一个元素，则更新 cursor 里的当前 index 和 当前 index 里对应的 lastValue。<br>在迭代时，如果到达页面边界时需要向上移动到父页面（从父页面再查找对应的孩子节点），当处于非叶页面时需要向下移动到叶页面，然后从叶子节点上根据 index 获取 value。<br>相关代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">hasNext</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-keyword">if</span> (cursorPos != <span class="hljs-literal">null</span>) &#123;<br>        <span class="hljs-type">int</span> <span class="hljs-variable">increment</span> <span class="hljs-operator">=</span> reverse ? -<span class="hljs-number">1</span> : <span class="hljs-number">1</span>;<br>        <span class="hljs-keyword">while</span> (current == <span class="hljs-literal">null</span>) &#123; <span class="hljs-comment">// 循环</span><br>            Page&lt;K,V&gt; page = cursorPos.page; <span class="hljs-comment">// 当前页面</span><br>            <span class="hljs-type">int</span> <span class="hljs-variable">index</span> <span class="hljs-operator">=</span> cursorPos.index; <span class="hljs-comment">// 从 pos 里获取当前 index</span><br>            <span class="hljs-keyword">if</span> (reverse ? index &lt; <span class="hljs-number">0</span> : index &gt;= upperBound(page)) &#123; <span class="hljs-comment">// 判断是否到达当前page的边界</span><br>                <span class="hljs-comment">// traversal of this page is over, going up a level or stop if at the root already</span><br>                CursorPos&lt;K,V&gt; tmp = cursorPos;<br>                cursorPos = cursorPos.parent; <span class="hljs-comment">// 如果 index 达到当前页的边界，则向上回溯到父节点</span><br>                <span class="hljs-keyword">if</span> (cursorPos == <span class="hljs-literal">null</span>) &#123;<br>                    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>                &#125;<br>                tmp.parent = keeper;<br>                keeper = tmp;<br>            &#125; <span class="hljs-keyword">else</span> &#123;<br>                <span class="hljs-comment">// traverse down to the leaf taking the leftmost path</span><br>                <span class="hljs-keyword">while</span> (!page.isLeaf()) &#123; <span class="hljs-comment">// 如果当前页不是叶子节点，则向下遍历到叶子节点</span><br>                    page = page.getChildPage(index);<br>                    index = reverse ? upperBound(page) - <span class="hljs-number">1</span> : <span class="hljs-number">0</span>;<br>                    <span class="hljs-keyword">if</span> (keeper == <span class="hljs-literal">null</span>) &#123;<br>                        cursorPos = <span class="hljs-keyword">new</span> <span class="hljs-title class_">CursorPos</span>&lt;&gt;(page, index, cursorPos);<br>                    &#125; <span class="hljs-keyword">else</span> &#123;<br>                        CursorPos&lt;K,V&gt; tmp = keeper;<br>                        keeper = keeper.parent;<br>                        tmp.parent = cursorPos;<br>                        tmp.page = page;<br>                        tmp.index = index;<br>                        cursorPos = tmp;<br>                    &#125;<br>                &#125;<br>                <span class="hljs-keyword">if</span> (reverse ? index &gt;= <span class="hljs-number">0</span> : index &lt; page.getKeyCount()) &#123;<br>                    <span class="hljs-type">K</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> page.getKey(index); <span class="hljs-comment">// 获取当前 page 指定 index 里存储的 key</span><br>                    <span class="hljs-keyword">if</span> (to != <span class="hljs-literal">null</span> &amp;&amp; Integer.signum(page.map.getKeyType().compare(key, to)) == increment) &#123;<br>                        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>                    &#125;<br>                    current = last = key;<br>                    lastValue = page.getValue(index); <span class="hljs-comment">// 根据 key 获取 value</span><br>                    lastPage = page;<br>                &#125;<br>            &#125;<br>            cursorPos.index += increment; <span class="hljs-comment">// 增加 index, 移动到下一个位置</span><br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> current != <span class="hljs-literal">null</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="代码流程"><a href="#代码流程" class="headerlink" title="代码流程"></a>代码流程</h2><h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/h2/h2database12-select.html">https://flyingzc.github.io/articles/h2/h2database12-select.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/H2/">H2</a><a class="post-meta__tags" href="/tags/Database/">Database</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/articles/h2/h2database01-build.html" title="H2 Database IDEA 环境搭建"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-08-20</div><div class="info-item-2">H2 Database IDEA 环境搭建</div></div><div class="info-2"><div class="info-item-1">H2 Database IDEA 源码 DEBUG 环境搭建基于最新的 version-2.3.230 拉取分支。 123git remote add h2 https://github.com/h2database/h2database.git git fetch h2git checkout -b version-2.3.230 version-2.3.230  使用12345# 启动java -jar h2*.jar# H2 shell 方式使用java -cp h2-*.jar org.h2.tools.Shell  h2 shell启动类 org.h2.tools.Shell 12# 配置启动参数-url &quot;jdbc:h2:~/test&quot; -user &quot;sa&quot; -password &quot;&quot;   测试 casecreate table + insert 1234567891011121314151617181920212223242526272829303132333435363738394041Welcome...</div></div></div></a><a class="pagination-related" href="/articles/h2/h2database02-mvstore-init.html" title="H2 Database MVStore 初始化"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-08-20</div><div class="info-item-2">H2 Database MVStore 初始化</div></div><div class="info-2"><div class="info-item-1">H2 Database MVStore 初始化作用MVStore（multi-version store）：H2 的默认存储子系统，支持多版本，持久化的、日志结构 的 键值存储。 功能123456789101112Maps    每个 store 包含多个 mvMaps,可以通过 java.util.Map 接口访问Versions    支持多版本Transactions    支持事务(并发事务&amp;两阶段提交)Concurrent Operations and Caching    支持并发读写Log Structured Storage    日志结构化存储支持文件存储和内存操作支持可插拔  文件存储格式12345# 文件存储格式[ file header 1 ] [ file header 2 ] [ chunk ] [ chunk ] ... [ chunk ]# chunk 存储格式[ header ] [ page ] [ page ] ... [ page ] [ footer ]  12345结构    File Header 文件头    Chunk...</div></div></div></a><a class="pagination-related" href="/articles/h2/h2database03-mvstore-commit.html" title="H2 Database MVStore Commit 流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-10-15</div><div class="info-item-2">H2 Database MVStore Commit 流程</div></div><div class="info-2"><div class="info-item-1">H2 Database MVStore Commit 流程作用BackgroundWriterThread 按照固定频率，将内存里修改的尚未保存的 Page 信息持久化到存储。 流程启动阶段创建后台线程org.h2.mvstore.MVStore#setAutoCommitDelay1.创建 BackgroundWriterThread 后台线程2.创建序列化线程 serializationExecutor3.创建持久化线程 bufferSaveExecutor设置自动提交更改的最大延迟（单位毫秒）。  默认值为 1000，这意味着所有更改最多在一秒后提交。  要禁用自动提交，需要将值设置为 0。在这种情况下，仅在显式调用 commit 时才会提交更改。 BackgroundWriterThread 线程逻辑定时任务周期性执行,比对内存里的 MVMap...</div></div></div></a><a class="pagination-related" href="/articles/h2/h2database06-transaction-commit.html" title="H2 Database 事务 Commit 流程实现原理"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-09-28</div><div class="info-item-2">H2 Database 事务 Commit 流程实现原理</div></div><div class="info-2"><div class="info-item-1">H2 Database 事务 Commit 流程实现原理使用测试 Demo: 123begin;insert into test values(1);commit;  功能模块类总体流程1234567891011121314解析 commit 语句执行 commit 语句    设置事务状态为已提交    根据 undoLogId 判断事务是否有更改操作,有更改继续提交    CAS 设置当前事务状态为已提交到 committingTransactions    遍历 undoLog mvMap        追加标记 undoLog 已提交到 undoLog mvMap 上        获取当前 undoLog 操作涉及的 mvMap id            遍历到对应 Page 的对应 index            将 VersionedValueUncommitted 类型更新成 DefaultRow 类型事务清理操作    清理 undoLog mvMap(更新 root 节点为 empty)    清理事务状态    释放 table...</div></div></div></a><a class="pagination-related" href="/articles/h2/h2database05-page.html" title="H2 Database MvMap 插入数据流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-10-12</div><div class="info-item-2">H2 Database MvMap 插入数据流程</div></div><div class="info-2"><div class="info-item-1">H2 Database MvMap 插入数据流程H2Database 使用 MVStore 作为默认的存储子系统，支持多版本，持久化的键值存储。其中每一个 MVMap 对象代表了一颗 btree。MVMap 里包含了 btree 根页面的引用，这颗 btree 可以表示一张表、一个索引，或者用来记录 undo log 等。 使用12345678// 1.根据数据库文件名称打开 mvStoreMVStore s = MVStore.open(fileName);// 2.指定名称创建 mvMapMVMap&lt;Integer, String&gt; map = s.openMap(&quot;data&quot;);// 3.将数据插入到 mvMap 上for (int i = 0; i &lt; 400; i++) &#123;    map.put(i, &quot;Hello-&quot; + i);&#125;  相关类MVMap 类成员变量包含了 MVMap 这个 btree 的唯一 id，btree 的根节点引用。btree 每个节点上存储的 key、value...</div></div></div></a><a class="pagination-related" href="/articles/h2/h2database06-transaction-isolation.html" title="H2 Database 事务隔离性实现原理"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-11-12</div><div class="info-item-2">H2 Database 事务隔离性实现原理</div></div><div class="info-2"><div class="info-item-1">H2 Database 事务隔离性实现原理使用测试 cases: 12345678910111213隔离级别 RC    A 开启事务    B 开启事务    B 插入数据并提交    A 可以读取到隔离级别 RR    A 开启事务    B 开启事务    A 查询    B 插入数据并提交    A 读取不到    A 自己插入数据    A 可以读取到自己插入的数据  功能H2 支持的事务隔离级别，定义在 IsolationLevel 里。包括 READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SNAPSHOT, SERIALIZABLE。其中 REPEATABLE_READ 不允许出现 脏读 和 不可重复读，但是允许出现幻读。SNAPSHOT 不允许出现 脏读 和 不可重复读 和 幻读。 12345678910111213141516171819202122232425262728293031323334/** * Level of isolation. */public enum IsolationLevel...</div></div></div></a></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#H2-Database-Select-%E8%AF%AD%E5%8F%A5%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B"><span class="toc-number">1.</span> <span class="toc-text">H2 Database Select 语句执行流程</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8"><span class="toc-number">1.1.</span> <span class="toc-text">使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8A%9F%E8%83%BD"><span class="toc-number">1.2.</span> <span class="toc-text">功能</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97"><span class="toc-number">1.3.</span> <span class="toc-text">模块</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B1%BB"><span class="toc-number">1.4.</span> <span class="toc-text">类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E4%BD%93%E6%B5%81%E7%A8%8B"><span class="toc-number">1.5.</span> <span class="toc-text">总体流程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%A3%E6%9E%90-%E4%BC%98%E5%8C%96"><span class="toc-number">1.5.1.</span> <span class="toc-text">解析&amp;优化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%A7%E8%A1%8C"><span class="toc-number">1.5.2.</span> <span class="toc-text">执行</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BF%AD%E4%BB%A3%E7%B4%A2%E5%BC%95%E8%8E%B7%E5%8F%96%E6%95%B0%E6%8D%AE"><span class="toc-number">1.5.2.1.</span> <span class="toc-text">迭代索引获取数据</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E6%B5%81%E7%A8%8B"><span class="toc-number">1.6.</span> <span class="toc-text">代码流程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83"><span class="toc-number">1.7.</span> <span class="toc-text">参考</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>